//
//  UIView+ViewController.m
//  YOYOLive
//
//  Created by wanggenqiang on 16/10/10.
//  Copyright © 2016年 wanggenqiang. All rights reserved.
//

#import "UIView+ViewController.h"

@implementation UIView (ViewController)

- (UIViewController *)viewController {
    UIResponder *next = self.nextResponder;
    do {
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        next = next.nextResponder;
    } while (next != nil);
    return nil;
}

#pragma mark ——————————点赞动画——————————
- (void)praise:(UIView *)view{
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(0, 0, 35, 35);
    dispatch_async(dispatch_get_main_queue(), ^{
        [view addSubview:imageView];
        imageView.transform = CGAffineTransformMakeScale(0.01, 0.01);
        [UIView animateWithDuration:0.3 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{
            imageView.transform = CGAffineTransformIdentity;
        } completion:nil];
        int imageName = arc4random() % 6;
        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"resource.bundle/heart%d.png",imageName]];
        // 位置
        CGPoint position = CGPointMake([UIScreen mainScreen].bounds.size.width - 50, [UIScreen mainScreen].bounds.size.height-50);
        CGFloat duration = 3 + arc4random()%5;
        CAKeyframeAnimation *positionAnimate = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        positionAnimate.repeatCount = 1;
        positionAnimate.duration = duration;
        positionAnimate.fillMode = kCAFillModeForwards;
        positionAnimate.removedOnCompletion = NO;
        UIBezierPath *sPath = [UIBezierPath bezierPath];
        [sPath moveToPoint:position];
        CGFloat sign = arc4random() % 2 == 1 ? 1 : -1;
        CGFloat controlPointValue = (arc4random() % 50 + arc4random() % 100) * sign;
        [sPath addCurveToPoint:CGPointMake(position.x, position.y - 300) controlPoint1:CGPointMake(position.x - controlPointValue, position.y - 150) controlPoint2:CGPointMake(position.x + controlPointValue, position.y - 150)];
        positionAnimate.path = sPath.CGPath;
        [imageView.layer addAnimation:positionAnimate forKey:@"heartAnimated"];
        [UIView animateWithDuration:3.0 animations:^{
            imageView.layer.opacity = 0;
        } completion:^(BOOL finished) {
            [imageView removeFromSuperview];
        }];
    });
}

- (UIViewController *)ViewController:(UIView *)view {
    UIResponder *responder = view;
    while ((responder = [responder nextResponder]))
        if ([responder isKindOfClass: [UIViewController class]])
            return (UIViewController *)responder;
    return nil;
}

@end

